
import posTpl from '../views/position.html'
import posAddTpl from '../views/positionAdd.html'
import posEditTpl from '../views/positionEdit.html'
import "../style/position.scss"
import router from '../router/index'
import handlebar from 'handlebars'
import { get, post } from '../model/http'

class PositionController {

  constructor() {
    this.keyword = "";
    this.pagesize = 100;
    this.pageno = 1;
    this.sortname = 'salary';
    this.sort = 'asc';
    this._initEvent();
  }

  async render(req, res) {
    console.log(req);
    if (req.query) {
      this.pagesize = req.query.pagesize;
      this.pageno = req.query.pageno;
      this.sortname = req.query.sortname;
      this.sort = req.query.sort;
      this.keyword = req.query.keyword;
    }
    this.res = res;
    //获取列表数据
    let dataset = await this._querylist()
    //生成html
    let html = this._createListHTML(dataset);
    console.log(html)
    res.render(html)
  }

  addRender(req, res) {
    res.render(posAddTpl)
  }

  async editRender(req, res) {
    let dataset = await get('/api/position/findone/' + req.params.id)
    let html = handlebar.compile(posEditTpl)(dataset.data)
    res.render(html)
  }



  _initEvent() {

    let self = this;

    let $container = $("#main-container");

    $container.on('click', '#position-add', () => router.go('/position/add'))

    //搜索
    $container.on('click', '#position-search', () => this._searchHandler())

    //新增数据的提交
    $container.on('click', '#btn-submit', () => this._addSubmit())

    //添加数据页面的返回按钮的事件
    $container.on('click', '#btn-back', () => router.go('/position/index'))

    //编辑页面，返回按钮的事件
    $container.on('click', '#posback', () => router.go('/position/index'))

    //编辑提交
    $container.on('click', '#btn-update', () => this._updateSubmit())

    //数据的删除
    $container.on('click', 'button[name="del"]', function () {
      let id = $(this).attr("data-id");
      self._delHandler(id);
    })

    //编辑按钮点击事件
    $container.on('click', 'button[name="edit"]', function () {
      let id = $(this).attr("data-id");
      router.go(`/position/edit/${id}`)
    })

    addEventListener('error', function (event) {
      if (event.target.tagName.toLowerCase() === 'img') {
        event.target.src = "/static/404.jpg"
      }
    }, false)

  }

  _addSubmit() {
    $("#position-add-form").ajaxSubmit({
      success: (result) => {
        alert(result.message)
        if (result.code === 1) {
          router.go('/position/index')
        }
      },
      error: (err) => {
        console.log(err);
      }
    })

  }

  _updateSubmit() {
    $("#position-update-form").ajaxSubmit({
      success: (result) => {
        alert(result.message)
        if (result.code === 1) {
          router.go('/position/index')
        }
      },
      error: (err) => {
        console.log(err);
      }
    })
  }

  async _delHandler(id) {
    let rs = await get(`/api/position/del/${id}`);
    alert(rs.message)
    if (rs.code === 1) {
      let dataset = await this._querylist()
      let html = this._createListHTML(dataset);
      this.res.render(html)
    }
  }

  //搜索
  async _searchHandler() {
    this.keyword = $("#search-txt").val();
    this.pageno = 1;
    let dataset = await this._querylist()
    let html = this._createListHTML(dataset);
    this.res.render(html)
  }

  _querylist() {
    let params = {
      keyword: this.keyword,
      pagesize: this.pagesize,
      pageno: this.pageno,
      sortname: this.sortname,
      sort: this.sort
    }
    return get('/api/position/list', params);
  }


  _createListHTML(dataset) {
    console.log('dataset', dataset)
    let total = dataset.total;
    let pages = [];
    let len = Math.ceil(total / this.pagesize);
    for (let i = 1; i <= len; i++) {
      pages.push(i)
    }
    let html = handlebar.compile(posTpl)({
      list: dataset.data,
      pages,
      pagesize: this.pagesize,
      pageno: this.pageno,
      keyword: this.keyword,
      sortname: this.sortname,
      sort: this.sort
    });

    //给页码添加active样式
    let timer = setTimeout(() => {
      $(".pagination ").find('li[data-id="' + this.pageno + '"]')
        .addClass('active').siblings().removeClass('active');
      clearTimeout(timer)
    }, 0)
    return html;
  }

}

export default new PositionController()